package com.itheima.test08;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/*

第四次版升级
可以不断的接收图片
并将所有的图片 都保存   UUID
使用多线程接收上传的图片
使用线程池 优化 线程的创建和销毁

创建服务器对象
接受数据
输入流
输入流保存到本地  创建输出流 写到服务器的

给 客户端响应
给结束标记
释放资源

 */
public class ServerDemo {

    public static void main(String[] args) throws IOException {
        //创建线程池
        ExecutorService pool = Executors.newCachedThreadPool();
        //创建服务器对象
        final ServerSocket ss = new ServerSocket(8888);
        while (true) {
            //接受数据
            Socket accept = ss.accept();
            UploadFile uploadFile = new UploadFile(accept);
           // new Thread(uploadFile).start();
            pool.submit(uploadFile);
        }


    }
}

class UploadFile implements Runnable {
    private Socket socket;

    public UploadFile(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        BufferedOutputStream bos = null;
        try {
            System.out.println(Thread.currentThread().getName()+"开始接受文件了");
            //输入流
            InputStream is = socket.getInputStream();
            //输入流保存到本地  创建输出流 写到服务器的
            bos = new BufferedOutputStream(new FileOutputStream("day16\\copy\\" + UUID.randomUUID() + ".png"));
            byte[] bytes = new byte[1024];
            int len;
            while ((len = is.read()) != -1) {//3mb=3000kb=30000000byte*1024
                bos.write(bytes, 0, len);
            }

            //给 客户端响应
            OutputStream os = socket.getOutputStream();
            //字符-> 字节
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os));
            writer.write("上传成功!");
            writer.flush();
            //os.close()
            //给结束标记
            socket.shutdownOutput();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //释放资源
            //ss.close();
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


    }
}
